package com.ontheroad.web.interceptor;

import com.ontheroad.core.annotation.QiniuUploadToken;
import com.ontheroad.qiniu.service.QiniuyunService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;

/**
 * 文件上传拦截器，生成文件上传token、domain
 *
 * Created by kedong on 2017/12/9 0009.
 */
public class FileUploadToken extends HandlerInterceptorAdapter {

    @Autowired
    private QiniuyunService qiniuyunService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if (handler instanceof HandlerMethod) {
            HandlerMethod handlerMethod = (HandlerMethod) handler;
            Method method = handlerMethod.getMethod();
            QiniuUploadToken annotation = method.getAnnotation(QiniuUploadToken.class);
            if (annotation != null) {
                String token = qiniuyunService.getUploadToken();
                String domain = qiniuyunService.getDomain();
                request.getSession(false).setAttribute("qiniuyun_upload_token", token);
                request.getSession(false).setAttribute("qiniuyun_upload_domain", domain);
            }
            return true;
        } else {
            return super.preHandle(request, response, handler);
        }
    }
}
